package cn.zyzpp.controller.user;

import cn.zyzpp.entity.job.NewJob;
import cn.zyzpp.entity.job.UserJob;
import cn.zyzpp.entity.user.User;
import cn.zyzpp.service.job.JobService;
import cn.zyzpp.service.job.UserJobService;
import cn.zyzpp.service.user.UserService;
import cn.zyzpp.util.FileUtil;
import cn.zyzpp.util.StringUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;


/**
 * Create by yster@foxmail.com 2018/5/17/017 18:41
 */
@Controller()
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private JobService jobService;
    @Autowired
    private UserJobService userJobService;
    @Autowired
    private HttpSession session;

    @RequestMapping("/login")
    public String loginPage() {
        if (session.getAttribute("uid") != null) {
            return "redirect:/";
        }
        //登录页面
        return "login";
    }

    @RequestMapping("/signIn")
    public String signInPage() {
        if (session.getAttribute("uid") != null) {
            return "redirect:/";
        }
        //注册页面
        return "signIn";
    }

    /**
     * 退出登录
     *
     * @return
     */
    @RequestMapping("/exit")
    public String exit() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/";
    }

    /**
     * 个人中心
     *
     * @return
     */
    @RequestMapping("/user")
    public String userPage(int id, ModelMap modelMap) {
        if (StringUtil.getIntBySessionUid(session) == id) {
            modelMap.addAttribute("or", 1);
        } else {
            modelMap.addAttribute("or", 0);
        }
        User user = userService.queryAll(id);
        List<UserJob> userJobList = userJobService.queryByUid(id);
        for (UserJob userJob : userJobList) {
            userJob.setNewJob(jobService.query(userJob.getJid()));
        }
        List<NewJob> jobList = jobService.queryAll(id);
        modelMap.addAttribute("user", user);
        modelMap.addAttribute("userjobList", userJobList);
        modelMap.addAttribute("jobList", jobList);
        for (NewJob job : jobList) {
            job.setNumber(userJobService.countByJid(job.getId()));
        }
        return "user";
    }

    @RequestMapping(value = "/signIn/result", method = RequestMethod.POST)
    public String userSignIn(User user, ModelMap model) {
        try {
            userService.userSingIn(user);
            return "login";
        } catch (Exception e) {
            model.addAttribute("msg", "该邮箱已被注册！");
            return "signIn";
        }
    }

    @RequestMapping(value = "/login/result", method = RequestMethod.POST)
    public String userLogin(User user, ModelMap model) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getMail(), user.getPassword());
        try {
            token.setRememberMe(user.isRememberMe());
            subject.login(token);
            User u = userService.queryAll(userService.getIdByUsername(user.getMail()));
            if (u.getOrUse() == 0) {
                subject.logout();
                model.addAttribute("msg", "该账号已被管理员冻结！");
                return "login";
            }
        } catch (Exception e) {
            model.addAttribute("msg", "输入有误！请重新输入");
            return "login";
        }
        session.setAttribute("uid", userService.getIdByUsername(user.getMail()));
        return "redirect:/";
    }

    @ResponseBody
    @RequiresRoles("user")
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String uploadImg(@RequestParam("file") MultipartFile file) throws Exception {
        if ("image".equals(file.getContentType().substring(0, 5))) {
            int uid = StringUtil.getIntByString(session.getAttribute("uid"));
            userService.saveUserImg(FileUtil.uploadFile(file, uid), uid);
            return "上传成功";
        }
        return "您上传的不是图片哦";
    }


    /**
     * 读取头像
     *
     * @param id
     * @param response
     * @throws IOException
     */
    @RequestMapping("/img/{id}")
    public void uploadPage(@PathVariable int id, HttpServletResponse response) throws IOException {
        byte[] bytes = FileUtil.getImg(userService.queryUserImg(id).getImgUrl());
        response.setContentType("image/png");
        OutputStream stream = response.getOutputStream();
        stream.write(bytes);
        stream.flush();
        stream.close();
    }

    @RequiresRoles("user")
    @RequestMapping("/upPass")
    public String upPassPage() {
        return "updataPassword";
    }

    @ResponseBody
    @RequiresRoles("user")
    @RequestMapping(value = "/upPass/result", method = RequestMethod.POST)
    public String upPass(String mail, String password) {
        int uid = StringUtil.getIntBySessionUid(session);
        User user = userService.queryAll(uid);
        if (user.getMail().equals(mail)) {
            userService.updataPassWord(mail,password);
            return "更新密码成功";
        }
        return "修改密码失败";
    }


}
